package nickthissen.iracing.activities;

import java.util.ArrayList;
import java.util.HashMap;

import nickthissen.iracing.common.Constants;
import nickthissen.iracing.common.DataLoader;
import nickthissen.iracing.common.Donations;
import nickthissen.iracing.common.Error;
import nickthissen.iracing.common.ForumListManager;
import nickthissen.iracing.common.ForumNames;
import nickthissen.iracing.common.Messages;
import nickthissen.iracing.common.PrivateStore;
import nickthissen.iracing.common.Redirect;
import nickthissen.iracing.common.ServiceLogging;
import nickthissen.iracing.common.Task;
import nickthissen.iracing.datamodels.Forum;
import nickthissen.iracing.datamodels.ForumList;
import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.datamodels.User;
import nickthissen.iracing.iracingforum2.R;
import nickthissen.iracing.networking.NetworkMethod;
import nickthissen.iracing.networking.Networking;
import nickthissen.iracing.parsing.ForumListParser;
import nickthissen.iracing.parsing.Parser;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;

public class MainActivity extends TaskActivity
{
    private static final String REDIRECT_URL = "REDIRECT_URL";
    private static final String REDIRECT_TYPE = "REDIRECT_TYPE";
    private static final String TRY = "TRY";
    private static final String FORUMLISTRESULT = "FORUMLISTRESULT";

	private Button btnForum, btnFavorites, btnPrivateMessages, btnRecent, btnPopular, btnOptions, btnLogout;

	private ForumList forumList;	
	private ProgressDialog dialog;	

    private boolean trialLoading = false;
	private Redirect redirect;

	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);  

        this.getSupportActionBar().setTitle("iRacing Forum Home");

        // Build UI
        btnForum = (Button) this.findViewById(R.id.btnForum);
        btnFavorites = (Button) this.findViewById(R.id.btnFavorites);
        btnPrivateMessages = (Button) this.findViewById(R.id.btnPM);
        btnRecent = (Button) this.findViewById(R.id.btnRecent);
        btnPopular = (Button) this.findViewById(R.id.btnPopular);
        btnOptions = (Button) this.findViewById(R.id.btnOptions);
        btnLogout = (Button) this.findViewById(R.id.btnLogout);

        TextView lblWelcome = (TextView) this.findViewById(R.id.lblWelcome);
        lblWelcome.setText("Welcome!"); // + User.currentUser.realname);

        setupAdvancedSettingsGesture();

        btnForum.setOnClickListener(new View.OnClickListener() {
						
        	@Override
			public void onClick(View v) {
				openForumList();
			}
		});
        btnFavorites.setOnClickListener(new View.OnClickListener() {
        	
        	@Override
        	public void onClick(View v) {
        		openFavorites();
        	}
        });
        btnPrivateMessages.setOnClickListener(new View.OnClickListener() {
			
        	@Override
			public void onClick(View v) {
				openPmList();				
			}
		});
        btnRecent.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				openRecentPopular(RecentPopularActivity.RECENT);
			}
		});
        btnPopular.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				openRecentPopular(RecentPopularActivity.POPULAR);
			}
		});
        btnOptions.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showOptions();
			}
		});
        btnLogout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				logout();
			}
		});


        // DEBUG!!!
//        ((Button)this.findViewById(R.id.btnClearCookies)).setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View v)
//            {
//                PrivateStore.clearCookies(MainActivity.this);
//            }
//        });

        // Get redirect parameters
        Bundle extras = savedInstanceState;
        if (extras == null)
        {
            Intent i = this.getIntent();
            extras = i.getExtras();
        }
        if (extras != null)
        {
        	redirect = new Redirect();
        	redirect.Url = extras.getString(REDIRECT_URL);
        	redirect.Type = extras.getInt(REDIRECT_TYPE);

            trialLoading = extras.getBoolean(TRY);
        }

        Donations.initialize(this);
        Donations.load(this);

        Messages.load(this);

        this.loadForumList();
    }

    @Override
    protected Task<Void> createTask()
    {
        return new Task<Void>(this, loadForumsTask);
    }

    @Override
    protected void saveTaskInput(Bundle state)
    {
    }

    @Override
    public Object restoreTaskInput(Bundle state)
    {
        return null;
    }

	public static Intent getIntent(Context context, Redirect redirect, boolean tryWithOldCookies)
	{
		Bundle bundle = new Bundle();
		if (redirect != null)
		{
			bundle.putString(REDIRECT_URL, redirect.Url);
			bundle.putInt(REDIRECT_TYPE, redirect.Type);
		}
        bundle.putBoolean(TRY, tryWithOldCookies);

		Intent intent = new Intent(context, MainActivity.class);
		intent.putExtras(bundle);
		return intent;
	}
	
	private void loadForumListFinished(boolean retryLogin)
	{
        if (retryLogin)
        {
            Toast.makeText(this, "Login may be expired, trying again...", Toast.LENGTH_LONG).show();
            PrivateStore.clearCookies(this);

            setResult(RESULT_CANCELED);
            finish();
            return;
        }

        setResult(RESULT_OK);

		if (redirect != null && redirect.Type > 0 && redirect.Url != null)
		{
			Redirect.loadRedirect(this, redirect);
		}
	}

	private void loadForumList()
	{
		dialog = ProgressDialog.show(this, "Loading", "Loading forum list and PMs...");
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                onCancelTask();
                dialog.dismiss();
            }
        });
		this.runTask(null);

        //this.runTask();

        ServiceLogging.logPageRequest(this, Networking.FORUMLIST_URL);
    }
	
	private void setPmCount()
	{
		int count = forumList.NewPmCount;
		if (count > 0)
		{
			btnPrivateMessages.setText("PM (" + count + ")");
		}
	}

	private void openForumList()
	{
		Intent intent = ForumListActivity.getIntent(this, forumList);
		this.startActivityForResult(intent, 0);		
	}
	
	private void openFavorites() 
	{
		Intent intent = FavoriteThreadsActivity.getIntent(this);
		this.startActivityForResult(intent, 0);
	}
	
	private void openPmList() 
	{
		Intent intent = PrivateMessageListActivity.getIntent(this);
		this.startActivityForResult(intent, 0);
	}
	
	private void openRecentPopular(int type)
	{
		Intent intent = RecentPopularActivity.getIntent(this, type);
		this.startActivityForResult(intent, 0);
	}
	
	private void showOptions()
	{
		Intent intent = new Intent(this, OptionsActivity.class);
		this.startActivityForResult(intent, 0);
	}
	
    private void logout()
    {
    	PrivateStore.clearLogin(this);
    	User.currentUser = null;
    	
    	this.startActivity(new Intent(this, LoginActivity.class));
    	this.finish();
    }
    
	private DataLoader<Void> loadForumsTask = new DataLoader<Void>()
	{
		public Result getData(Void in)
		{
			// Obtain forum list page source
			Result result = Networking.getForumList(this.getContext());
			
			if (result.Success)
			{
				// Parse source and return forumlist result
				String source = (String)result.Object;
                ForumListParser parser = new ForumListParser();
                parser.context = this.getContext();
				Result parseResult = parser.parse(source);
                parseResult.Status = result.Status;
                return parseResult;
			}
			else
			{
				// Error
				return result;
			}
		}
		
		public void onFinished(Result out)
		{
            boolean retryLogin = false;

			if (out.Success) 
			{
                if (out.Status.getStatusCode() != 200)
                {
                    Log.i(Constants.TAG, "Status code '" + out.Status.getStatusCode() + "' when loading forum list, send to login.");
                    // Something wrong
                    retryLogin = true;
                }

				// Set forum items in list
				forumList = (ForumList)out.Object;
				
				ForumListManager.getInstance().forums = new HashMap<Integer, Forum>();
				for (Forum f : forumList.Forums)
				{
					ForumListManager.getInstance().forums.put(f.Id, f);
				}				
			}
			else
			{
				// Error
				forumList = new ForumList();
				forumList.Forums = new ArrayList<Forum>();
				
				Error error = Error.fromResult(out);

                if (trialLoading)
                {
                    error.log(this.getContext());
                }
                else
                {
				    error.report(this.getContext());
                }

                retryLogin = true;
			}

            ForumNames.load(this.getContext());

			setProgressBarIndeterminateVisibility(false);
			
			setPmCount();

			if (dialog != null)
			{
				dialog.dismiss();
				dialog = null;
			}
			
			loadForumListFinished(retryLogin);
		}
	};

    private static int clicks = 0;
    private void setupAdvancedSettingsGesture()
    {
        TextView lblVersion = (TextView) this.findViewById(R.id.lblVersion);

        lblVersion.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                clicks += 1;
                Handler handler = new Handler();
                Runnable r = new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Log.i("AdvancedOptions", "Timed out.");
                        clicks = 0;
                    }
                };

                if (clicks == 1)
                {
                    Log.i("AdvancedOptions", "First click.");
                    handler.postDelayed(r, 1500);
                }
                else if (clicks == 7)
                {
                    Log.i("AdvancedOptions", "Success.");
                    clicks = 0;
                    showAdvancedSettings();
                }
            }
        });
    }

    private void showAdvancedSettings()
    {
        Intent i = new Intent(this, AdvancedOptionsActivity.class);
        this.startActivityForResult(i, 0);
    }
}
